package com.bosssoft.hr.train.springmvc.example.interceptor;

import com.bosssoft.hr.train.springmvc.example.dao.UserDao;
import com.bosssoft.hr.train.springmvc.example.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @description 自定义验证拦截器 拦截处理登录以外所有url请求并判断用户的登录状态
 * @author ChenTong
 * @date 2020/6/5
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    UserDao userDao;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws ServletException, IOException {
        String uri = httpServletRequest.getRequestURI();
        log.info("被拦截uri：{}",uri);
        //除了login 其余请求获取拦截
        if (uri.indexOf("/boss/login")>=0)
            return true;
        //从session中获取用户信息
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        //通过拦截
        if (user != null){
            log.info("user已登录 通过拦截");
            return true;
        }
        log.info("user未登录 拦截");
        //未通过进行转发-> login.jsp
        httpServletRequest.setAttribute("msg","未登录，请先登录");
        httpServletRequest.getRequestDispatcher("/jsp/login.jsp").forward(httpServletRequest,httpServletResponse);

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // DO NOTHING
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
        // DO NOTHING
    }


}
